package com.njrsrc.common.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;

import com.njrsrc.android.bean.Image;

public class UploadImage {
	private static UploadImage instance;
	
	private String multipart_form_data = "multipart/form-data";   
    private String twoHyphens = "--";   
    private String boundary = java.util.UUID.randomUUID().toString();   // 数据分隔符    
    private String lineEnd = "\r\n";    // The value is "\r\n" in Windows.  
	
	private UploadImage(){};
	
	public static UploadImage getInstance()
	{
		if(instance == null)
		{
			instance = new UploadImage();
		}
		return instance;
	}
	
	/**  
     * 直接通过 HTTP 协议提交数据到服务器，实现表单提交功能。  
     * @param actionUrl 上传路径  
     * @param params 请求参数key为参数名，value为参数值  
     * @param files 上传文件信息  
     * @return 返回请求结果  
     */   
    public String post(String actionUrl, Set<Map.Entry<String,String>> params, Image[] files) {   
        HttpURLConnection conn = null;   
        DataOutputStream output = null;   
        BufferedReader input = null;   
        try {   
            URL url = new URL(actionUrl);   
            conn = (HttpURLConnection) url.openConnection();   
            conn.setConnectTimeout(120000);   
            conn.setDoInput(true);        // 允许输入    
            conn.setDoOutput(true);        // 允许输出    
            conn.setUseCaches(false);    // 不使用Cache    
            conn.setRequestMethod("POST");   
            conn.setRequestProperty("Connection", "keep-alive");   
            conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);   
               
            conn.connect();   
            output = new DataOutputStream(conn.getOutputStream());   
               
            addImageContent(files, output);    // 添加图片内容    
               
            addFormField(params, output);    // 添加表单字段内容    
               
            output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);// 数据结束标志    
            output.flush();   
               
            int code = conn.getResponseCode();   
            if(code == 200) {   
            	 input = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
                 StringBuilder response = new StringBuilder();   
                 String oneLine;   
                 while((oneLine = input.readLine()) != null) {   
                     response.append(oneLine + lineEnd);   
                 }   
                 return response.toString();   
            }   
            return null;
        } catch (IOException e) {   
            throw new RuntimeException(e);   
        } finally {   
            // 统一释放资源    
            try {   
                if(output != null) {   
                    output.close();   
                }   
                if(input != null) {   
                    input.close();   
                }   
            } catch (IOException e) {   
                throw new RuntimeException(e);   
            }   
               
            if(conn != null) {   
                conn.disconnect();   
            }   
        }   
    }   
	
	private void addImageContent(Image[] files, DataOutputStream output) {   
        for(Image file : files) {   
            StringBuilder split = new StringBuilder();   
            split.append(twoHyphens + boundary + lineEnd);   
            split.append("Content-Disposition: form-data; name=\"" + file.formName + "\"; filename=\"" + file.fileName + "\"" + lineEnd);   
//            split.append("Content-Type: " + file.type + lineEnd);   
            split.append(lineEnd); 
            FileInputStream fStream = null;
            try {   
                // 发送图片数据    
                output.writeBytes(split.toString());  
                
                /* 取得文件的FileInputStream */
                fStream = new FileInputStream(file.path);
                /* 设置每次写入1024bytes */
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                /* 从文件读取数据至缓冲区 */
                while((length = fStream.read(buffer)) != -1)
                {
                  /* 将资料写入DataOutputStream中 */
                	output.write(buffer, 0, length);
                }
                output.writeBytes(lineEnd);   
            } catch (IOException e) {   
                throw new RuntimeException(e);   
            }   finally
            {
            	if(fStream != null)
            	{
            		try {
						fStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
            	}
            }
        }   
    }  
	
	  private void addFormField(Set<Map.Entry<String,String>> params, DataOutputStream output) {   
	        StringBuilder sb = new StringBuilder();   
	        for(Map.Entry<String, String> param : params) {   
	            sb.append(twoHyphens + boundary + lineEnd);   
	            sb.append("Content-Disposition: form-data; name=\"" + param.getKey() + "\"" + lineEnd);   
	            sb.append(lineEnd);   
	            sb.append(param.getValue() + lineEnd);   
	        }   
	        try {   
	            output.writeBytes(sb.toString());// 发送表单字段数据    
	        } catch (IOException e) {   
	            throw new RuntimeException(e);   
	        }   
	    }   
	
	

}
